package com.itboye.api.controller;

import com.itboye.config.GlobalConfig;
import com.itboye.system.helper.ByConfigHelper;
import com.itboye.system.crypt.ByDataCrypt;
import com.itboye.system.exception.ByBaseException;
import com.itboye.system.helper.ByConsoleHelper;
import com.itboye.api.model.ByResponseData;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * Created by hebidu on 16/5/9.
 */
@ControllerAdvice
public class ExceptionController {

    private static final Logger logger = LogManager.getLogger(ExceptionController.class.toString());

    /**
     * 从RequestContextHolder获取
     * @return HttpServletRequest
     */
    private HttpServletRequest getRequest(){
        return ((ServletRequestAttributes)(RequestContextHolder.currentRequestAttributes())).getRequest();
    }

    @ExceptionHandler({ByBaseException.class})
    @ResponseBody
    public String exceptionHandler(Exception ex) throws NoSuchAlgorithmException, UnsupportedEncodingException, ByBaseException {

        return customExceptionInfo(ex).toJson();
    }

    private ByResponseData customExceptionInfo(Exception ex) throws UnsupportedEncodingException, ByBaseException {

        ByConsoleHelper.info(ex.getLocalizedMessage(),logger);

        HttpServletRequest request = getRequest();

        String notifyId =  GlobalConfig.DEFAULT_NOTIFY_ID;
        if(request != null){
             notifyId = request.getParameter("notify_id");
        }

        if(notifyId == null || notifyId.length() == 0){
            notifyId = GlobalConfig.DEFAULT_NOTIFY_ID;
        }

        String clientId = GlobalConfig.DEFAULT_CLIENT_ID;
        if(request != null) {
            clientId = request.getParameter("client_id");
        }

        if(clientId == null || clientId.length() == 0){
            clientId = GlobalConfig.DEFAULT_CLIENT_ID;
        }

        String strData =  ex.getMessage();
        String code = "-500";

        if(ex.getClass().equals(ByBaseException.class)){
            code  = ((ByBaseException)ex).getCode();
        }
        ByConsoleHelper.debug("code="+code+","+strData,logger);
        ByConsoleHelper.debug("clientId= "+clientId+"notifyId= "+notifyId,logger);

        try {
            ByResponseData responseData = ByResponseData.fail(code,strData,GlobalConfig.DEFAULT_CLIENT_SECRET,notifyId);
            responseData.setClientId(clientId);
            return responseData;
        } catch (UnsupportedEncodingException e) {
            ByConsoleHelper.info(e.getLocalizedMessage(),logger);
        } catch (ByBaseException e) {
            ByConsoleHelper.info(e.getLocalizedMessage(),logger);
        }

        return ByResponseData.DEFAULT("服务器发生异常了");
    }

}
